/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.market.web.controller;

import com.market.web.EJB.AllItems;
import com.market.web.EJB.CustomerFacade;
import com.market.web.EJB.InventoryFacade;
import com.market.web.EJB.OrderTransaction;
import com.market.web.EJB.TempshoppingcartFacade;
import com.market.web.model.Customer;
import com.market.web.model.Inventory;
import com.market.web.model.Item;
import com.market.web.model.Tempshoppingcart;
import com.market.web.model.TempshoppingcartPK;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.List;
import javax.ejb.EJB;
import javax.inject.Inject;
import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObjectBuilder;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.glassfish.sse.api.ServerSentEventContext;
import org.glassfish.sse.api.ServerSentEventData;
import org.glassfish.sse.api.ServerSentEventHandlerContext;

/**
 *
 * @author Mai
 */
@WebServlet({"/getProductList","/products","/shoppingCart","/removeCart","/checkOut","/checkShoppingCart","/successOrder.html"})
public class getProductController extends HttpServlet {

    @EJB
    private InventoryFacade inventoryFacade;
    
    @EJB
    private TempshoppingcartFacade tempShoppingCartFacade;
    
    @EJB
    private CustomerFacade customerFacade;

    @EJB
    private OrderTransaction orderTrans;
    
    @Override
    public void init() throws ServletException {
        super.init(); //To change body of generated methods, choose Tools | Templates.
        
    }
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     

        String userPath = req.getServletPath();
        System.out.println(userPath);
        HttpSession session = req.getSession(false);
        Customer c = (Customer) session.getAttribute("cust");
        
        if (userPath.equals("/products")) 
        {
            if(c == null)
            {
                resp.sendRedirect("login2.html");
            }
            else
            {
                 resp.sendRedirect("productList.html");
            }
            
        }
        else if (userPath.equals("/getProductList")) 
        {     
             if(c == null)
            {
                RequestDispatcher rd = req.getRequestDispatcher("/login2.html");
                rd.forward(req, resp);
                return;
            }
            else
            {
                List<Inventory> lstInventory = inventoryFacade.findAll();

                JsonArrayBuilder items = Json.createArrayBuilder();

                for (Inventory inv : lstInventory) {
                    JsonObjectBuilder item = Json.createObjectBuilder();
                    item.add("pId", inv.getPid());
                    item.add("pName", inv.getName());
                    item.add("pPrice", inv.getPrice());
                    item.add("pQty", inv.getQty());
                    item.add("pImg", inv.getImageName());
                    if(inv.getType()!=null)
                    {
                        item.add("pType", inv.getType());
                    }

                    if(inv.getDescription()!=null)
                    {
                        item.add("pDesc", inv.getDescription());
                    }

                    items.add(item);
                }
                resp.setStatus(HttpServletResponse.SC_OK);
                resp.setContentType("application/json");
                resp.setHeader("Phrase", "I rock!");
                //System.out.println(getServletContext().getAttribute("CurrentCust"));
                try (PrintWriter pw = resp.getWriter()) {
                    pw.println(items.build().toString());
                } 
            

            }
        }
       
        else if (userPath.equals("/checkShoppingCart")) {
            AllItems lst  = (AllItems) session.getAttribute("items");
            Item scItem;
            
            if(lst==null)
            {
                
                List<Tempshoppingcart> temp = tempShoppingCartFacade.getTempSCByCID(c);
                if(temp == null)
                {
                    System.out.println("session is null");
                }
                else
                {
                    System.out.println("there is something in the session");
                
                    JsonArrayBuilder scItems = Json.createArrayBuilder();

                    for(Tempshoppingcart tempItem: temp)
                    {
                        JsonObjectBuilder itemJson = Json.createObjectBuilder();


                        itemJson.add("pId", tempItem.getTempshoppingcartPK().getPid());
                        itemJson.add("pName", tempItem.getName());
                        itemJson.add("pPrice", tempItem.getPrice());
                        itemJson.add("pQty", tempItem.getItemQty());

                        Inventory inv = inventoryFacade.find(tempItem.getTempshoppingcartPK().getPid());

                        itemJson.add("qtyInStore",inv.getQty());
                        
                        scItems.add(itemJson);

                    }
                    tempShoppingCartFacade.removeTempSCByCID(c);
                    
                    resp.setStatus(HttpServletResponse.SC_OK);
                    resp.setContentType("application/json");
                    resp.setHeader("Phrase", "I rock!");

                    try (PrintWriter pw = resp.getWriter()) {
                        pw.println(scItems.build().toString());
                    } 
                }

            }
            else
            {
                
                System.out.println("there is something in the session");
                
                
                JsonArrayBuilder scItems = Json.createArrayBuilder();

                for (Item shoppingCartItem: lst.getItems()) {
                    JsonObjectBuilder itemJson = Json.createObjectBuilder();
                    
                    
                    itemJson.add("pId", shoppingCartItem.getId());
                    itemJson.add("pName", shoppingCartItem.getName());
                    itemJson.add("pPrice", shoppingCartItem.getPrice());
                    itemJson.add("pQty", shoppingCartItem.getQty());
                    
                    Inventory inv = inventoryFacade.find(shoppingCartItem.getId());
                    
                    itemJson.add("qtyInStore",inv.getQty());
                    
                    scItems.add(itemJson);

                }
                
                resp.setStatus(HttpServletResponse.SC_OK);
                resp.setContentType("application/json");
                resp.setHeader("Phrase", "I rock!");

                try (PrintWriter pw = resp.getWriter()) {
                    pw.println(scItems.build().toString());
                } 
                
                
            }
        }
       else if (userPath.equals("/successOrder.html")) 
       {
           DecimalFormat df = new DecimalFormat("#.00");
           
           
           AllItems lst  = (AllItems) session.getAttribute("items");
           try (PrintWriter pw = resp.getWriter()) {
            pw.println("<html><body>");
            pw.println("<h1>Thank You for shopping with Us</h1>");
            pw.println("<h4>Here are your order list!!!!</h4>");
            pw.println("<table border='1'>");
            pw.println("<tr>");
            pw.println("<td>Prdouct Name");
            pw.println("</td>");
            pw.println("<td>Unit Price");
            pw.println("</td>");
            pw.println("<td>Quantity");
            pw.println("</td>");
            pw.println("<td>Sub Total");
            pw.println("</td>");
            pw.println("</tr>");
            for(Item i: lst.getItems())
            {
                pw.println("<tr>");
                pw.println("<td>" + i.getName());
                pw.println("</td>");
                pw.println("<td>" + df.format(i.getPrice()));
                pw.println("</td>");
                pw.println("<td>" + i.getQty());
                pw.println("</td>");
                pw.println("<td>" + df.format(i.getSubTotal()));
                pw.println("</td>");
                pw.println("</tr>");
            }
            pw.println("<tr>");
            pw.println("<td colspan='3'>Grand Total");
            pw.println("</td>");
            pw.println("<td>" + df.format(lst.getTotal()));
            pw.println("</td>");
            pw.println("</table>");
            pw.println("</body></html>");
            pw.println("<h5>Please check your email to receive invoice</h5>");
            pw.println("<a href='products'>Go Back Prdouct List</a>");
            pw.println("<a href='logout'>Log Out</a>");
            lst.emptyCart();
            session.removeAttribute("items");
            //session.invalidate();
            }
       }
        
    }

    @Inject @ServerSentEventContext("/invUpdate")
    ServerSentEventHandlerContext<InventoryConnection> connections;
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        
        String userPath = req.getServletPath();
        
        HttpSession session = req.getSession();
        Customer c = (Customer) session.getAttribute("cust");
        AllItems items  = (AllItems) session.getAttribute("items");
        Item item;
        
       
        
        
        if(userPath.equals("/shoppingCart")) 
        {
             int id = Integer.parseInt(req.getParameter("pId"));
             String name = req.getParameter("pName");
             double price = Double.parseDouble(req.getParameter("pPrice"));
             int qty = Integer.parseInt(req.getParameter("pQty"));
             
             
            if (items == null) {
                
                items = new AllItems();
                session.setAttribute("items", items);
            }

            item = new Item(id,name,price,qty);
            items.addItem(item);
            
            if(items.getCustomer()==null)
            {
                items.setCustomer(c);
            }
            
            //--------start of server sent event------------

            //pId:id, pName:name, pPrice:price, pQty:qty, qtyleft:qtyInStore
            
            //int sseId = Integer.parseInt(req.getParameter("pId"));
            String sseId = req.getParameter("pId");
            String sseName = req.getParameter("pName");
            double ssePrice = Double.parseDouble(req.getParameter("pPrice"));
            int sseQty = Integer.parseInt(req.getParameter("pQty"));
            int sseQtyLeft= Integer.parseInt(req.getParameter("qtyleft"));
            
            
            ServerSentEventData data = new ServerSentEventData();
            JsonObjectBuilder b = Json.createObjectBuilder();
            //b.add("jId", sseId);
            b.add("jName",sseName);
            b.add("jPrice",ssePrice);
            b.add("jQty",sseQty);
            b.add("jQtyLeft",sseQtyLeft);
            
            data.data(b.build().toString());
            data.event(sseId);
            for(InventoryConnection i: connections.getHandlers() )
                i.send(data);
            resp.setContentType("text/plain");
            resp.setStatus(HttpServletResponse.SC_OK);
            
//            String message = req.getParameter("message");
//            String roomName = req.getParameter("roomName");
//
//            System.out.println("----> the message: " + message);
//            System.out.println("---> roomName: " + roomName);
//
//            ServerSentEventData data = new ServerSentEventData();
//            JsonObjectBuilder b = Json.createObjectBuilder();
//            b.add("text", message)
//                    .add("time", new Date().toString());
//            data.data(b.build().toString());
//            data.event(roomName);
//            for (ChatConnection c: connections.getHandlers())
//                c.send(data);                
//
//            resp.setContentType("text/plain");
//            resp.setStatus(HttpServletResponse.SC_OK);
            
            //------------end of server sent event-----------------
            
//            for(Item i: items.getItems())
//            {
//                System.out.println("start again-----------------------------");
//                System.out.println("pid" + i.getId());
//                System.out.println("pQty" + i.getQty());
//                System.out.println("pName ------->" + i.getName());
//                System.out.println("total ---->" + i.getSubTotal());
//            }
//            System.out.println("Grand Total ----->" +items.getTotal() );
        }
        else if (userPath.equals("/removeCart")) 
        {
            
            if(req.getParameter("pId")!=null)
            {
                items.emptyOne(Integer.parseInt(req.getParameter("pId")));
            }
            else
            {
                items.emptyCart();
                session.removeAttribute("items");
                System.out.println(items.getTotal());
                //session.invalidate();
            }
            
        }
        else if (userPath.equals("/checkOut")) 
        {
            //AllItems shoppingItems = (AllItems)session.getAttribute("items");
            
            
            int oId = orderTrans.makeOrder(c, items);
            
            //to check there is temporary shopping cart item in the database
            //if it has, will delete all records
            List<Tempshoppingcart> ts;
            ts = tempShoppingCartFacade.getTempSCByCID(c);
            
            if(ts!=null)
            {
                tempShoppingCartFacade.removeTempSCByCID(c);
            }
            
            RequestDispatcher rd = req.getRequestDispatcher("MailApp?OrderId="+oId);
            rd.forward(req, resp);
            
//            Tempshoppingcart ts;
//            ts = tempShoppingCartFacade.getTempSCByCID(c);
//            
//            if(ts!=null)
//            {
//                tempShoppingCartFacade.remove(ts);
//            }
//            resp.setContentType("text/html");
//            resp.setStatus(HttpServletResponse.SC_OK);
        
            
//            for(Item i:shoppingItems.getItems())
//            {
//                System.out.println("Items in the carts-----------");
//                System.out.println("pid     ----->" + i.getId());
//                System.out.println("pQty    ----->" + i.getQty());
//                System.out.println("pName   ----->" + i.getName());
//                System.out.println("total   ----->" + i.getSubTotal());
//            }
//            System.out.println("Grand Total ----->" +shoppingItems.getTotal() );

        }
        else if (userPath.equals("/logout")) 
        {
            
            if(items.getTotal() >0)
            {
                for(Item i: items.getItems())
                {
                    TempshoppingcartPK tPK = new TempshoppingcartPK();
                    tPK.setCustID(c.getCustId());
                    tPK.setPid(i.getId());
                    Tempshoppingcart  t = new Tempshoppingcart();
                    t.setItemQty(i.getQty());
                    t.setName(i.getName());
                    BigDecimal b = new BigDecimal(i.getPrice());
                    t.setPrice(b);
                    t.setTempshoppingcartPK(tPK);
                    
                    tempShoppingCartFacade.create(t);
                }
            }
            
            
            
            
        }
      
       
    }
    
    
    
            
}